<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>学生信息管理系统</title>
    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
</head>
<body>

<h2>学生信息管理系统</h2>

<!-- 操作按钮 -->
<div id="actionButtons">
    <button id="addBtn" class="btn btn-primary" onclick="showModal()">
        <i class="fas fa-plus"></i> 添加学生
    </button>
    <button id="editBtn" class="btn btn-info" style="display:none;" onclick="editStudent()">
        <i class="fas fa-edit"></i> 编辑
    </button>
    <button id="deleteBtn" class="btn btn-danger" style="display:none;" onclick="deleteSelectedStudents()">
        <i class="fas fa-trash-alt"></i> 删除
    </button>
</div>

<table id="studentTable" class="table">
    <thead>
    <tr>
        <th><input type="checkbox" id="selectAll" onclick="toggleSelectAll()"></th>
        <th>学号</th>
        <th>姓名</th>
        <th>性别</th>
        <th>出生日期</th>
        <th>创建时间</th>
        <th>更新时间</th>
    </tr>
    </thead>
    <tbody></tbody>
</table>

<!-- 弹窗 -->
<div class="modal" id="addModal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 id="modalTitle">添加学生</h3>
        </div>
        <form id="studentForm">
            <div class="form-group">
                <label for="newName">姓名：</label>
                <input type="text" id="newName" autocomplete="off" class="form-control" required />
            </div>
            <div class="form-group">
                <label for="newGender">性别：</label>
                <select id="newGender" class="form-control" required>
                    <option value="男">男</option>
                    <option value="女">女</option>
                </select>
            </div>
            <div class="form-group">
                <label for="newBirthday">出生日期：</label>
                <input type="date" id="newBirthday" class="form-control" required />
            </div>
            <div class="modal-footer">
                <button class="btn btn-success" type="submit">
                    <i class="fas fa-save"></i> 保存
                </button>
                <button type="button" class="btn btn-secondary" onclick="hideModal()">
                    <i class="fas fa-times"></i> 取消
                </button>
            </div>
        </form>
    </div>
</div>

<script>
    let editingStudentNo = null;
    let selectedStudents = [];

    // 加载学生信息
    function loadStudents() {
        fetch('/student/list')
            .then(res => res.json())
            .then(data => {
                const tbody = document.querySelector('#studentTable tbody');
                tbody.innerHTML = '';
                data.forEach(stu => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td><input type="checkbox" class="studentCheckbox" data-id="${stu.sutdentNo}" onclick="toggleSelectStudent(this)"></td>
                        <td>${stu.sutdentNo}</td>
                        <td>${stu.name}</td>
                        <td>${stu.gender}</td>
                        <td>${stu.birthday ? stu.birthday.split('T')[0] : ''}</td>
                        <td>${stu.createTime ? stu.createTime.replace('T', ' ').substring(0,19) : ''}</td>
                        <td>${stu.updateTime ? stu.updateTime.replace('T', ' ').substring(0,19) : ''}</td>
                    `;
                    tbody.appendChild(row);
                });
            });
    }

    // 选中/取消选中一行
    function toggleSelectStudent(checkbox) {
        const studentId = checkbox.dataset.id;
        if (checkbox.checked) {
            selectedStudents.push(studentId);
        } else {
            selectedStudents = selectedStudents.filter(id => id !== studentId);
        }
        toggleActionButtons();
    }

    // 选中/取消选中所有行
    function toggleSelectAll() {
        const selectAllCheckbox = document.getElementById("selectAll");
        const checkboxes = document.querySelectorAll(".studentCheckbox");
        checkboxes.forEach(checkbox => {
            checkbox.checked = selectAllCheckbox.checked;
            toggleSelectStudent(checkbox);
        });
    }

    // 根据选中的记录更新操作按钮状态
    function toggleActionButtons() {
        const editBtn = document.getElementById("editBtn");
        const deleteBtn = document.getElementById("deleteBtn");

        if (selectedStudents.length === 1) {
            editBtn.style.display = "inline-block";
        } else {
            editBtn.style.display = "none";
        }

        if (selectedStudents.length > 0) {
            deleteBtn.style.display = "inline-block";
        } else {
            deleteBtn.style.display = "none";
        }
    }

    // 删除选中的学生
    function deleteSelectedStudents() {
        if (confirm('确认删除选中的学生吗？')) {
            const promises = selectedStudents.map(studentNo => {
                return fetch(`/student/${studentNo}`, {
                    method: 'DELETE'
                });
            });

            Promise.all(promises).then(responses => {
                responses.forEach(res => {
                    if (res.ok) {
                        alert('删除成功');
                    } else {
                        alert('删除失败');
                    }
                });
                loadStudents();
                selectedStudents = [];
                toggleActionButtons();
            });
        }
    }

    // 编辑选中的学生
    function editStudent() {
        if (selectedStudents.length === 1) {
            editingStudentNo = selectedStudents[0];
            const studentRow = document.querySelector(`.studentCheckbox[data-id="${editingStudentNo}"]`).parentElement.parentElement;
            const cells = studentRow.getElementsByTagName("td");

            // 填充模态框数据
            document.getElementById("newName").value = cells[2].textContent.trim();
            document.getElementById("newGender").value = cells[3].textContent.trim();
            document.getElementById("newBirthday").value = cells[4].textContent.trim();

            document.getElementById("modalTitle").innerText = "编辑学生";
            showModal();
        }
    }

    // 显示模态框
    function showModal() {
        document.getElementById("addModal").style.display = "flex";
    }

    // 隐藏模态框
    function hideModal() {
        document.getElementById("addModal").style.display = "none";
        document.getElementById('studentForm').reset(); // 清空表单
    }

    // 保存学生信息（添加或编辑）
    function saveStudent(event) {
        event.preventDefault();
        const name = document.getElementById('newName').value.trim();
        const gender = document.getElementById('newGender').value.trim();
        const birthday = document.getElementById('newBirthday').value;

        if (!name || !gender || !birthday) {
            alert("请填写完整且正确的姓名、性别、出生日期");
            return;
        }

        const currentTime = new Date().toISOString();

        const studentData = {
            name,
            gender,
            birthday,
            createTime: currentTime,  // 添加创建时间
            updateTime: currentTime   // 添加更新时间
        };

        let method = 'POST';
        let url = '/student';

        if (editingStudentNo) {
            method = 'PUT';
            url = `/student/${editingStudentNo}`;
            studentData.sutdentNo = editingStudentNo;
            studentData.updateTime = currentTime;  // 更新修改时间
        }

        fetch(url, {
            method,
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(studentData)
        }).then(res => {
            if (res.ok) {
                alert("保存成功！");
                hideModal();
                loadStudents();
                editingStudentNo = null; // 重置编辑标志
            } else {
                alert("保存失败！");
            }
        });
    }

    // 监听表单提交
    document.getElementById('studentForm').addEventListener('submit', saveStudent);

    window.onload = loadStudents;
</script>

</body>
</html>
